﻿using System;
using Chat.Common;

/// <summary>
/// 命令发送器,用于向服务器发送数据
/// </summary>
public  class CommandSender
{
    /// <summary>
    /// 像服务器发送控制命令
    /// </summary>
    /// <param name="ctlType">欲发送的控制命令类型</param>
    /// <param name="param">控制参数</param>
    public void SendControlCmd(ControlType ctlType,string param=null)
    {
        string str = ctlType.ToString();
        if(String.IsNullOrEmpty(str))
            throw new Exception("ctlType is null or empty……");
        if (str.Length > Common.ctlTypeSize)
            throw new Exception("ctlType length overflow……");
        else
        {
            str = str + Common.GetLoopStr(" ", Common.ctlTypeSize - str.Length);
            Send(Common.rcvDataHead, CommandType.Control.ToString(), str+param, Common.rcvDataTail);
        }
    }
    /// <summary>
    /// 向服务器发送一条聊天消息
    /// </summary>
    /// <param name="msg">聊天消息,必须包含接收者信息</param>
    public void SendChatMsg(Message msg)
    {
        string str = msg.ChatType.ToString();
        if (String.IsNullOrEmpty(str))
            throw new Exception("chatType is null or empty……");
        if (str.Length > Common.chtTypeSize)
            throw new Exception("chatType length overflow……");
        else
        {
            str = str + Common.GetLoopStr(" ", Common.chtTypeSize - str.Length);
            Send(Common.rcvDataHead, CommandType.Chat.ToString(), str + msg.Receiver.Id + msg.Content, Common.rcvDataTail);
        }
    }
    /// <summary>
    /// 向聊天室服务端发送命令
    /// </summary>
    /// <param name="cmdHead">命令头</param>
    /// <param name="cmdType">命令类型</param>
    /// <param name="cmd">命令</param>
    /// <param name="cmdTail">命令尾</param>
    private void Send(string cmdHead, string cmdType, string cmd, string cmdTail)
    {
        if (cmdHead.Length > Common.cmdHeadSize)
            throw new Exception("The cmdHead length overflow……");
        if (cmdType.Length > Common.cmdTypeSize)
            throw new Exception("The cmdType length overflow……");
        if (cmdTail.Length > Common.cmdTailSize)
            throw new Exception("The cmdTail length overflow……");

        if (cmdHead.Length < Common.cmdHeadSize)
            cmdHead = cmdHead + Common.GetLoopStr(" ", Common.cmdHeadSize - cmdHead.Length);
        if (cmdType.Length < Common.cmdTypeSize)
            cmdType = cmdType + Common.GetLoopStr(" ", Common.cmdTypeSize - cmdType.Length);
        if (cmdTail.Length < Common.cmdTailSize)
            cmdTail = cmdTail + Common.GetLoopStr(" ", Common.cmdTailSize - cmdTail.Length);

        Singleton<ChatClient>.GetInstance().Send(cmdHead + cmdType + cmd + cmdTail);
    }
}
